# 创建精灵类
import random

import pygame

# 屏幕大小
SCREEN_RECT = pygame.Rect(0, 0, 480, 700)


class GameSprites(pygame.sprite.Sprite):
    def __init__(self, image_name, speed=1):
        super().__init__()
        # 加载图像
        # 并且在精灵组绘制的时候会使用该图像
        self.image = pygame.image.load(image_name)
        # image.get_rect() 方法可以获取该图像的rect图形,获取到的图形的x和y默认是0,width和height是图像的宽高
        # 定义rect图形
        # 并且在精灵族绘制的时候,会使用rect图型的坐标来当做被绘制图像的坐标
        self.rect = self.image.get_rect()
        self.speed = speed

    def update(self):
        self.rect.y += self.speed


class Background(GameSprites):

    def __init__(self, is_alt=False):
        super().__init__('./images/background.png')
        if is_alt:
            self.rect.y = -self.rect.height

    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.height:
            self.rect.y = -SCREEN_RECT.height


class Enemy(GameSprites):
    def __init__(self):
        super().__init__('./images/enemy1.png')
        self.speed = random.randint(1, 3)
        self.rect.bottom = 0
        self.rect.x = random.randint(0, SCREEN_RECT.width - self.rect.width)

    def update(self):
        super().update()
        if self.rect.y >= SCREEN_RECT.height:
            # 销毁通过该精灵类创建的精灵
            self.kill()


class Hero(GameSprites):
    def __init__(self):
        super().__init__('./images/me1.png', 0)
        self.rect.centerx = SCREEN_RECT.centerx
        self.rect.bottom = SCREEN_RECT.bottom - 120
        # 创建子弹精灵组
        self.bullet_group = pygame.sprite.Group()

    def update(self):
        self.rect.x += self.speed
        if self.rect.x <= 0:
            self.rect.x = 0
        elif self.rect.right >= SCREEN_RECT.right:
            # right = x + rect.width
            self.rect.right = SCREEN_RECT.right

    def fire(self):
        bullet = Bullet()
        bullet.rect.bottom = self.rect.y
        bullet.rect.centerx = self.rect.centerx
        self.bullet_group.add(bullet)
        print('发射子弹...')


class Bullet(GameSprites):
    def __init__(self):
        super().__init__('./images/bullet1.png', -2)

    def update(self):
        super().update()
        if self.rect.bottom <= 0:
            self.kill()

    def __del__(self):
        print('子弹销毁了')
